package com.atguigu.filter;

import com.alibaba.fastjson2.JSON;
import com.atguigu.Utils.BaseContext;
import com.atguigu.Utils.R;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import java.io.IOException;

@WebFilter
@Slf4j
public class loginFilter implements Filter {
    public  static  final AntPathMatcher PATH_MATCHER = new AntPathMatcher();//路径匹配器
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        HttpServletResponse response=(HttpServletResponse)servletResponse;
        log.info("拦截到请求:{}",request.getRequestURI());
        log.info("线程id：{}",Thread.currentThread().getId());


        String requestURI = request.getRequestURI();
        String [] urls = new String[]{//不需要登陆判断的url
          "/employee/login",
          "/employee/logout",
          "/backend/**",
          "/front/**",
          "/common/**",
          "/user/login",
          "/user/sendMsg",
        };//不处理的uri

        if(check(urls,requestURI)){//如果不需要判断，直接放行
            filterChain.doFilter(request,response);
            return;
        }
        if (request.getSession().getAttribute("employee")!=null) {//判断是否员工登录

            Object attribute = request.getSession().getAttribute("employee");
            Long id = (Long)attribute;
            BaseContext.setThreadLocal(id);

            filterChain.doFilter(request,response);

            log.info("员工已登录");
            return;
        }

        if (request.getSession().getAttribute("user")!=null) {//判断是否用户登录

            Object attribute = request.getSession().getAttribute("user");
            Long id = (Long)attribute;
            BaseContext.setCurrentId(id);

            filterChain.doFilter(request,response);

            log.info("用户已登录");
            return;
        }

       response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }


    public boolean check(String[]urls,String requestURI){
        for (String url : urls) {
            if(PATH_MATCHER.match(url,requestURI)){
                return true;
            }
        }

        return false;
    }
}
